package com.woniu.payment.controller;

import com.woniu.api.order.OrderClient;
import com.woniu.common.entity.Order;
import com.woniu.common.entity.dto.PaymentNotification;
import com.woniu.common.exception.Assert;
import com.woniu.common.result.Result;
import com.woniu.common.entity.dto.PaymentRequest;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mane
 * @since 2025-03-29
 */
@RestController
@RequestMapping("/api/payment")
public class PaymentController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderClient orderClient;

    /**
     * 处理支付请求
     * @param orderId 订单ID (路径变量)
     * @param request 支付请求体
     * @return 支付结果
     */
    @PostMapping("/{order_id}")
    public Result<Map<String, String>> processPayment(
            @PathVariable("order_id") Integer orderId,
            @RequestBody @Valid PaymentRequest request) {

        try {
            // 1. 验证订单是否存在（示例逻辑）
            Result<Order> result = orderClient.getOrderById(orderId);
            Order order = result.getData();
            Assert.error(order==null,"订单不存在");
            // 2. 处理支付（示例调用支付服务）
            // 3. 返回成功响应
            Map<String, String> response = new HashMap<>();
            response.put("message", "支付成功");
            response.put("order_id", orderId.toString());
            //4.mq发送消息给队列
            sendPaymentNotification(order);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("支付失败",600);
        }
    }
    public void sendPaymentNotification(Order order) {
        PaymentNotification notification = new PaymentNotification(order.getId(), "PAID");
        rabbitTemplate.convertAndSend("paymentExchange", "payment.key", notification);
    }
}
